<%@page import="com.nj9you.wxpay.config.WXProperty"%>
<%@page import="com.github.wxpay.sdk.WXPayUtil"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.Locale"%>
<%@ page import="java.util.Map" %>
<%@ page import="org.apache.log4j.Logger" %>
<%!
    Logger logger = Logger.getLogger("jsp_notify");
    private String generateSuccessResult() {
        StringBuilder builder = new StringBuilder();
        builder.append("<xml>").append("\n");
        builder.append("    ").append("<return_code><![CDATA[SUCCESS]]></return_code>").append("\n");
        builder.append("    ").append("<return_msg><![CDATA[OK]]></return_msg>").append("\n");
        builder.append("</xml>");
        return builder.toString();
    }

    private String generateFailureResult(String msg) {
        StringBuilder builder = new StringBuilder();
        builder.append("<xml>").append("\n");
        builder.append("    ").append("<return_code><![CDATA[FAIL]]></return_code>").append("\n");
        builder.append("    ").append(String.format(Locale.getDefault(), "<return_msg><![CDATA[%s]]></return_msg>", msg)).append("\n");
        builder.append("</xml>");
        return builder.toString();
    }

    private String readHttpBody(InputStream is) {
        try {
            StringBuilder builder = new StringBuilder();
            int read = 0;
            byte buf [] = new byte[1024];
            while((read = is.read(buf)) > 0) {
                builder.append(new String(buf, 0, read, "UTF-8"));
            }
            return builder.toString();
        } catch(Exception e) {
        }
        return null;
    }
%>
<%
    request.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Type", "text/plain");

    String body = readHttpBody(request.getInputStream());
    boolean valid = false;
    try {
        if (body != null && !body.trim().equals("")) {
            valid = WXPayUtil.isSignatureValid(body, WXProperty.get("app_key"));
        }
    } catch(Exception e) {
    }
    logger.debug("valid : " + valid);
    if (valid) {
        Map<String, String> map = null;
        try {
            map = WXPayUtil.xmlToMap(body);
        } catch(Exception e) {
        }
        out.clearBuffer();
        out.print(generateSuccessResult());
    } else {
        out.clearBuffer();
        out.print(generateFailureResult("签名不正确"));
    }
%>